package com.wxy.controller;
import com.wxy.dao.UserDao;
import com.wxy.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping()
public class JumpController {
    @Autowired
    private UserDao userDao;

    @GetMapping(value = "/who")
    public String who() {
        // 跳转到 视图层 login.html
        return "pages/data.html";
    }
    public boolean confirm(List<User> list,String username,String password){
        for(User item : list){
            if(item.getUsername().equals(username)){
                if (item.getPassword().equals(password))
                    return true;
                else
                    return false;
            }

        }
        return false;
    }
    public boolean confirm2(List<User> list,String username,String password){
        for(User item : list){
            if(item.getUsername().equals(username)){
                    return true;
            }
        }
        return false;
    }
    @ResponseBody
    @PostMapping("/login")
    public Result login(HttpServletRequest request,HttpServletResponse response,@RequestBody User user) throws ServletException, IOException {
        List<User> list = userDao.selectList(null);
        boolean flag = confirm(list,user.getUsername(),user.getPassword());
        Integer code = flag?Code.LOGIN_OK : Code.LOGIN_ERR;
        String msg = flag?"登陆成功":"登录失败";
        return new Result(code,flag,msg);
    }

    @ResponseBody
    @PostMapping("/register")
    public Result register(HttpServletRequest request,HttpServletResponse response,@RequestBody User user) throws ServletException, IOException {
        List<User> list = userDao.selectList(null);
        boolean flag = confirm2(list,user.getUsername(),user.getPassword());
        if(!flag){
            userDao.insert(user);
        }
        Integer code = !flag?Code.REGISTER_OK : Code.REGISTER_ERR;
        String msg = !flag?"注册成功":"注册失败,账户已存在请登录";
        return new Result(code,flag,msg);
    }

    @RequestMapping(value = "/getJson", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, String> getJson() {
        Map<String, String> all = new HashMap<>();
        all.put("remark", "结合注解 @ResponseBody 返回接送");
        return all;
    }
}
